import { useState, useCallback } from 'react';
import { createModel } from 'hox';

function useRealtimeMessageModel() {
  const [visible, setVisible] = useState(false);
  const [state, setState] = useState({
    socket: null,
    record: [],
  });

  const dispatch = payload => {
    setState(prevState => {
      return { ...prevState, ...payload };
    });
  };

  const closeSocket = () => {
    setState(prevState => {
      prevState.socket && prevState.socket.disconnect();
      setVisible(false);
      return { socket: null };
    });
  };
  const clearRecord = () => {
    dispatch({ record: [] });
  };

  const updateRecord = item => {
    setState(prevState => {
      let newRecord = [item, ...prevState.record];
      let newState = { ...prevState, record: newRecord };
      return {
        ...newState,
      };
    });
  };

  return {
    ...state,
    clearRecord,
    dispatch,
    visible,
    setVisible,
    updateRecord,
    closeSocket,
  };
}

export default createModel(useRealtimeMessageModel);
